package org.zjt.agent.bytebuddy;

import net.bytebuddy.agent.builder.AgentBuilder;
import net.bytebuddy.agent.builder.ResettableClassFileTransformer;
import net.bytebuddy.description.type.TypeDescription;
import net.bytebuddy.dynamic.DynamicType;
import net.bytebuddy.implementation.FixedValue;
import net.bytebuddy.implementation.MethodDelegation;
import net.bytebuddy.matcher.ElementMatcher;
import net.bytebuddy.matcher.ElementMatchers;
import net.bytebuddy.utility.JavaModule;

import java.lang.instrument.Instrumentation;

import static net.bytebuddy.matcher.ElementMatchers.*;
import static net.bytebuddy.matcher.ElementMatchers.named;
import static net.bytebuddy.matcher.ElementMatchers.not;

/**
 * @author juntao.zhang
 * @version V1.0
 * @Description: TODO
 * @Package org.zjt.agent.bytebuddy
 * @date 2017/12/3 13:20
 */
public class Agent {

    public static void premain(String arguments, Instrumentation instrumentation) {
        System.out.printf("----------premain-----arguments:%s-----instrumentation:%s------\n",arguments,instrumentation);
        new AgentBuilder.Default()
                .type(nameStartsWith(arguments).and(not(isInterface())).and(not(isStatic())))
                .transform((builder,typeDescription,classLoader,module) -> builder
                        .method(ElementMatchers.any())
                        .intercept(MethodDelegation.to(Interceptor.class)
                        )
                ).with(new AgentBuilder.Listener(){

             @Override
             public void onDiscovery(String typeName, ClassLoader classLoader, JavaModule module, boolean loaded) {

             }

             @Override
             public void onTransformation(TypeDescription typeDescription, ClassLoader classLoader, JavaModule module, boolean loaded, DynamicType dynamicType) {

             }

             @Override
             public void onIgnored(TypeDescription typeDescription, ClassLoader classLoader, JavaModule module, boolean loaded) {

             }

             @Override
             public void onError(String typeName, ClassLoader classLoader, JavaModule module, boolean loaded, Throwable throwable) {
                 throwable.printStackTrace();
             }

             @Override
             public void onComplete(String typeName, ClassLoader classLoader, JavaModule module, boolean loaded) {

             }
         }).installOn(instrumentation);
    }

}
